package admin_middleware

import (
	"gitee.com/theegg/go-brick/app/model/admin/admin_users"
	"gitee.com/theegg/go-brick/app/model/user/users"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/carray"
	"gitee.com/theegg/go-brick/app/service/help/cjwt"
	"github.com/gin-gonic/gin"
	"strings"
)

var ignoreRoute = []string{"/mpi/admin/login"}

func TokenAdminMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 去除所有路径
		path := c.FullPath()
		if carray.IsStringInArray(path, ignoreRoute) {
			c.Next()
			return
		}

		// 获取token
		tokenString := c.Request.Header.Get("Authorization")
		if tokenString == "" {
			app.NewResponse(c).ErrorReturn(app.UnauthorizedTokenError)
			c.Abort()
			return
		}

		tokenArr := strings.Split(tokenString, " ")
		token := tokenArr[1]

		// 解析token
		claim, err := cjwt.NewTokenContainer("admin").ParseToken(token)
		if err != nil {
			app.NewResponse(c).ErrorReturn(app.UnauthorizedTokenError.WithData(err.Error()))
			c.Abort()
			return
		}

		if claim == nil {
			app.NewResponse(c).ErrorReturn(app.UnauthorizedTokenError)
			c.Abort()
			return
		}

		encodeUserId := claim.UserId

		userId, err := users.DecodeUserId(encodeUserId)
		if err != nil {
			app.NewResponse(c).ErrorReturn(app.UnauthorizedTokenError.WithData(err.Error()))
			c.Abort()
			return
		}

		adminUser, err := admin_users.GenCurrentUser(userId)
		if err != nil {
			app.NewResponse(c).ErrorReturn(app.UnauthorizedTokenError.WithData("token-gen-current-user-" + err.Error()))
			c.Abort()
		}

		ok, err := adminUser.CheckToken(token)

		if err != nil || !ok {
			app.NewResponse(c).ErrorReturn(app.UnauthorizedTokenError.WithData("token已过期，或未登陆!"))
			c.Abort()
			return
		}

		// 用户帮定
		c.Set("c_admin_user", adminUser)

		c.Next()
	}

}
